package com.fivium.bpd.editor;

import java.awt.BorderLayout;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.swing.mxGraphOutline;
import com.mxgraph.view.mxGraph;

public class GraphPanel extends JPanel
{
  private mxGraphComponent graphComponent_;
  private mxGraphOutline graphOutline_;
  
  public GraphPanel(mxGraphComponent graphComponent)
  {
    graphComponent_ = graphComponent;
    final mxGraph graph = graphComponent.getGraph();
    
    graph.setAlternateEdgeStyle("edgeStyle=mxEdgeStyle.ElbowConnector;elbow=vertical");
    
    // Creates the graph outline component
    graphOutline_ = new mxGraphOutline(graphComponent);

    GraphPalette palette = new GraphPalette();
    
    JScrollPane paletteScrollPane = new JScrollPane(palette);
    paletteScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    paletteScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    
    // Creates the inner split pane that contains the library with the
    // palette and the graph outline on the left side of the window
    JSplitPane paletteAndOutlineSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    paletteAndOutlineSplitPane.setResizeWeight(0.7d);
    paletteAndOutlineSplitPane.add(paletteScrollPane);
    paletteAndOutlineSplitPane.add(graphOutline_);
    
    // Creates the outer split pane that contains the inner split pane and
    // the graph component on the right side of the window
    JSplitPane container = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    container.setDividerLocation(200);
    container.add(paletteAndOutlineSplitPane);
    container.add(graphComponent_);

    // Puts everything together
    setLayout(new BorderLayout());
    add(container, BorderLayout.CENTER);
    
    registerListeners();
  }
  
  private void registerListeners()
  {
    // Installs mouse wheel listener for zooming
    MouseWheelListener wheelTracker = new MouseWheelListener()
    {

      public void mouseWheelMoved(MouseWheelEvent e)
      {
        if (e.getSource() instanceof mxGraphOutline || e.isControlDown())
        {
          GraphPanel.this.mouseWheelMoved(e);
        }
      }
    };

    // Handles mouse wheel events in the outline and graph component
    graphOutline_.addMouseWheelListener(wheelTracker);
    graphComponent_.addMouseWheelListener(wheelTracker);
  }
  
  
  private void mouseWheelMoved(MouseWheelEvent e)
  {
    if (e.getWheelRotation() < 0)
    {
      graphComponent_.zoomIn();
    }
    else
    {
      graphComponent_.zoomOut();
    }

    //status(mxResources.get("scale") + ": "
    //    + (int) (100 * graphComponent.getGraph().getView().getScale())
    //    + "%");
  }
}
